剑指 Offer 30. 包含min函数的栈

1. Question

定义栈的数据结构,请在该类型中实现一个能够得到栈的最小元素的 min 函数在该栈中,调用 min、push 及 pop 的时间复杂度都是 O(1)。

2. Examples

示例:

MinStack minStack = new MinStack();
minStack.push(-2);
minStack.push(0);
minStack.push(-3);
minStack.min();   --> 返回 -3.
minStack.pop();
minStack.top();      --> 返回 0.
minStack.min();   --> 返回 -2.

3. Constraints

各函数的调用总次数不超过 20000 次

4. References

来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/bao-han-minhan-shu-de-zhan-lcof 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

5. Solutions

class MinStack {

    Deque<Integer> input;
    Deque<Integer> sorted;

    /** initialize your data structure here. */
    public MinStack() {
        input = new LinkedList<>();
        sorted = new LinkedList<>();
    }

    public void push(int x) {
        input.push(x);

        //  避免重复的最小值被弹出
        if (sorted.isEmpty() || sorted.peek() >= x) {
            sorted.push(x);
        }
    }

    public void pop() {
        if (sorted.peek().equals(input.pop())) {
            sorted.pop();
        }
    }

    public int top() {
        return input.peek();
    }

    public int min() {
        return sorted.peek();
    }
}

/**
 * Your MinStack object will be instantiated and called as such:
 * MinStack obj = new MinStack();
 * obj.push(x);
 * obj.pop();
 * int param_3 = obj.top();
 * int param_4 = obj.min();
 */
Copyright © rootwhois.cn 2021-2022 all right reserved,powered by GitbookFile Modify: 2023-03-05 10:55:51

results matching ""

    No results matching ""